<?php

require_once 'modules/exercise/Models/Folder.php';
require_once 'modules/content/models/ContentCategory.php';
require_once 'modules/Exercise/Models/ExerciseLib.php';
require_once 'modules/Exercise/Models/ExerciseParameter.php';

require_once 'Nine/Folder.php';

class Exercise_AdminController extends Nine_Controller_Action_Admin
{
	
	public function newExerciseParaAction()
	{
		$objExercise = new Models_ExerciseParameter() ;
		$objExerciseLib = new Models_ExerciseLib();
		$objLang = new Models_Lang();
		$allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
		$this->view->allLangs = $allLangs;
		$user_login = Nine_Registry::getLoggedInUserId();
		//         echo "<pre>";print_r($user_login);die;
		/**
		 * Check permission
		 */
		if (false == $this->checkPermission('new_exercise', null, '?')) {
			$this->_forwardToNoPermissionPage();
			return;
		}
		
		$data = $this->_getParam('data', false);
// 		echo "<pre>";print_r($data);die;
		if (false !== $data) {
			/**
			 * Insert new content
			 */
			$newContent = $data;
			$newContent['created_date'] = time();
			$newContent['user_id'] = $user_login;
			/**
			 * Slipt intro_text & full_text
			 */
		
			try {
// 		echo "<pre>";print_r($newContent);die;
				$objExercise->insert($newContent);
				//               	echo "HERE";die;
				/**
				 * Message
				 */
				$this->session->contentMessage =  array(
						'success' => true,
						'message' => Nine_Language::translate('Exercise is created successfully.')
				);
				//                echo "<pre>HERE";die;
				$this->_redirect('exercise/admin/manage-exercise-para');
			} catch (Exception $e) {
				$errors = array('main' => Nine_Language::translate('Can not insert into database now'));
			}
		} else {
// 			$data = array('sorting' => 1);
		}
		$allExerciseLib = $objExerciseLib->getAll()->toArray();
		$this->view->data = $data;
		$this->view->exerciseLib = $allExerciseLib;
		$this->view->headTitle(Nine_Language::translate('New Exercise'));
        $this->view->menu = array('exercise', 'newexercise');
        $this->view->fullPermisison = $this->checkPermission('new_exercise', null, '*'); 
//         echo "<pre>";print_r($this->checkPermission('new_exercise', null, '*'));die;
		
	}
	public function editExerciseParaAction()
	{
		$objExercise = new Models_ExerciseParameter() ;
		$objExerciseLib = new Models_ExerciseLib();
		$objLang = new Models_Lang();
		$allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
		$this->view->allLangs = $allLangs;
		$user_login = Nine_Registry::getLoggedInUserId();
		//         echo "<pre>";print_r($user_login);die;
		/**
		 * Check permission
		 */
		if (false == $this->checkPermission('new_exercise', null, '?')) {
			$this->_forwardToNoPermissionPage();
			return;
		}
		$gid     = $this->_getParam('gid', false);
		$data = $this->_getParam('data', false);
		$allContentLangs = $objExercise->setAllLanguages(true)->getByColumns(array('exercise_parameter_gid=?' => $gid))->toArray();
		// 		echo "<pre>";print_r($data);die;
		if (false !== $data) {
			/**
			 * Insert new content
			 */
			$newContent = $data;
			$newContent['created_date'] = time();
			$newContent['user_id'] = $user_login;
			/**
			 * Slipt intro_text & full_text
			 */
	
			try {
				$objExercise->update($newContent, array('exercise_parameter_gid=?' => $gid));
				/**
				 * Message
				 */
				$this->session->contentMessage =  array(
						'success' => true,
						'message' => Nine_Language::translate('Exercise is created successfully.')
				);
				//                echo "<pre>HERE";die;
				$this->_redirect('exercise/admin/manage-exercise-para');
			} catch (Exception $e) {
				$errors = array('main' => Nine_Language::translate('Can not insert into database now'));
			}
		} else {
			$data = @reset($allContentLangs);
			
			if (false == $data) {
				$this->session->exerciseMessage = array(
						'success' => false,
						'message' => Nine_Language::translate("Exercise doesn't exist.")
				);
				$this->_redirect('exercise/admin/manage-exercise-para');
			}
			foreach ($allContentLangs as $content) {
				/**
				 * Rebuild readmore DIV
				 */
// 				$content['description'] = Nine_Function::combineTextWithReadmore($content['intro_text'], $content['full_text']);
				$data[$content['lang_id']] = $content;
			}
			
		}
		$allExerciseLib = $objExerciseLib->getAll()->toArray();
		$this->view->data = $data;
		$this->view->exerciseLib = $allExerciseLib;
		$this->view->headTitle(Nine_Language::translate('New Exercise'));
		$this->view->menu = array('exercise', 'newexercise');
		$this->view->fullPermisison = $this->checkPermission('new_exercise', null, '*');
		//         echo "<pre>";print_r($this->checkPermission('new_exercise', null, '*'));die;
	
	}
	public function manageExerciseParaAction()
	{
		$objExercise = new Models_ExerciseParameter();
		$objExerciseLib = new Models_ExerciseLib();
		$this->view->headTitle(Nine_Language::translate('manage Exercise '));
		$this->view->menu = array('exercise', 'manageexercise');
	
		$config = Nine_Registry::getConfig();
		$numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
		$currentPage = $this->_getParam("page",1);
		$displayNum = $this->_getParam('displayNum', false);
	
		$data = $this->_getParam('data', array());
		/**
		 * Get number of items per page
		 */
		if (false === $displayNum) {
			$displayNum = $this->session->exerciseDisplayNum;
		} else {
			$this->session->exerciseDisplayNum = $displayNum;
		}
		if (null != $displayNum) {
			$numRowPerPage = $displayNum;
		}
		/**
		 * Get condition
		 */
		$condition = $this->_getParam('condition', false);
		if (false === $condition) {
			$condition = $this->session->exerciseCondition;
		} else {
			$this->session->exerciseCondition = $condition;
			$currentPage = 1;
		}
		if (false == $condition) {
			$condition = array();
		}
	
		/**
		 * Get all categories
		 */
		 
		$allCats = $objExerciseLib->getAll()->toArray();
		$this->view->allCats = $allCats;
// 		echo "<pre>";print_r($allCats);die;
	
		/**
		 * Get all products
		 */
		// 		echo "<pre>";print_r($condition);die;
		$allExercises = $objExercise->setAllLanguages(true)->getAllExercisePara($condition, array( 'exercise_parameter_id DESC'),
				$numRowPerPage,
				($currentPage - 1) * $numRowPerPage
		);
		// 		       echo '<pre>';print_r($allFolders);die;
		/**
		 * Count all products
		 */
		$count = count($objExercise->getAllExercisePara($condition));
		$tmp = array();
		foreach ($allExercises as $index=>$item) {
	
	
			/**
			 * Change date
			 */
			if (0 != $item['created_date']) {
				$item['created_date'] = date($config['dateFormat'], $item['created_date']);
			} else {
				$item['created_date'] = '';
			}
			if (0 != $item['update_date']) {
				$item['update_date'] = date($config['dateFormat'], $item['update_date']);
			} else {
				$item['update_date'] = '';
			}
	
			array_push($tmp, $item);
	
	
		}
		$allExercises = $tmp;
	
		/**
		 * Prepare for template
		 */
		$date = time();
		$date = date('d/m/Y', $date);
	
		$this->view->date = $date;
	
		// 	echo "<pre>";print_r($allLectures);die;
	
		/**
		 * Set values for tempalte
		 */
	
		//echo '<pre>';print_r($allFolders);die;
	
		$this->setPagination($numRowPerPage, $currentPage, $count);
		$this->view->allExercises = $allExercises;
		$this->view->exerciseMessage = $this->session->exerciseMessage;
		$this->session->exercisefolderMessage = null;
		$this->view->condition = $condition;
		$this->view->displayNum = $numRowPerPage;
		$this->view->fullPermisison = $this->checkPermission('see_exercise');
	
	}
	public function manageFolderAction()
	{
		$objFolder = new Models_Folder();
		$objCat     = new Models_ContentCategory();
		$this->view->headTitle(Nine_Language::translate('manage Demo'));
		$this->view->menu = array('exercise', 'managedemo');
		
		$config = Nine_Registry::getConfig();
		$numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
		$currentPage = $this->_getParam("page",1);
		$displayNum = $this->_getParam('displayNum', false);
		
		$data = $this->_getParam('data', array());
		/**
		 * Get number of items per page
		 */
		if (false === $displayNum) {
			$displayNum = $this->session->folderDisplayNum;
		} else {
			$this->session->folderDisplayNum = $displayNum;
		}
		if (null != $displayNum) {
			$numRowPerPage = $displayNum;
		}
		/**
		 * Get condition
		 */
		$condition = $this->_getParam('condition', false);
		if (false === $condition) {
			$condition = $this->session->folderCondition;
		} else {
			$this->session->folderCondition = $condition;
			$currentPage = 1;
		}
		if (false == $condition) {
			$condition = array();
		}
		
		/**
		 * Get all categories
		 */
		$this->view->allCats = $objCat->getAll()->toArray();
		
		/**
		 * Get all products
		 */
// 		echo "<pre>";print_r($condition);die;
		$allFolders = $objFolder->getAllFolders($condition, array( 'folder_id DESC'),
				$numRowPerPage,
				($currentPage - 1) * $numRowPerPage
		);
// 		       echo '<pre>';print_r($allFolders);die;
		/**
		 * Count all products
		 */
		$count = count($objFolder->getAllFolders($condition));
		$tmp = array();
		foreach ($allFolders as $index=>$item) {
		
				
			/**
			 * Change date
			 */
			if (0 != $item['created_date']) {
				$item['created_date'] = date($config['dateFormat'], $item['created_date']);
			} else {
				$item['created_date'] = '';
			}
			if (0 != $item['update_date']) {
				$item['update_date'] = date($config['dateFormat'], $item['update_date']);
			} else {
				$item['update_date'] = '';
			}
				
			array_push($tmp, $item);
				
				
		}
		$allFolders = $tmp;
		
		/**
		 * Prepare for template
		 */
		$date = time();
		$date = date('d/m/Y', $date);
		
		$this->view->date = $date;
		
		// 	echo "<pre>";print_r($allLectures);die;
		
		/**
		 * Set values for tempalte
		 */
		
		//echo '<pre>';print_r($allFolders);die;
		
		$this->setPagination($numRowPerPage, $currentPage, $count);
		$this->view->allFolders = $allFolders;
		$this->view->folderMessage = $this->session->folderMessage;
		$this->session->folderMessage = null;
		$this->view->condition = $condition;
		$this->view->displayNum = $numRowPerPage;
		$this->view->fullPermisison = $this->checkPermission('see_product');
		
	}
	public function newFolderAction()
	{
		$objFolder = new Models_Folder();
		$objCat = new Models_ContentCategory();
		$allCats = $objCat->getAll()->toArray();
		/**
		 * Check permission
		 */
// 		if (false == $this->checkPermission('new_transaction', null, '?')) {
// 			$this->_forwardToNoPermissionPage();
// 			return;
// 		}
		
		$data = $this->_getParam('data', false);
		
		
		$errors = array();
		if (false !== $data) {
			/**
			 * Insert 
			 */
			$newFolder = array(
				 'title' => $data['title'],
				 'description' => $data['description'],
				 'subject_id' => $data['subject_id'],
				 'created_date' => time(),
				 'update_date' => time()
				 
				 );
			/**
			 * Remove empty files
			 */
			if (is_array(@$data['file'])) {
				foreach ($data['file'] as $index => $file) {
					if (null == $file) {
						unset($data['file'][$index]);
					} else {
						$data['file'][$index] = Nine_Function::getImagePath($file);
					}
				}
			}
			$newFolder['files'] = implode('||', $data['file']);
//			try {
// 		echo "<pre>";print_r($newFolder);die;
				$idFolder = $objFolder->insert($newFolder);
				$this->_redirect('exercise/admin/manage-folder');
		
//			} catch (Exception $e) {
//				$errors = array('main' => Nine_Language::translate('Can not insert into database now'));
//			}
		}
		/**
		* Prepare for template
		*/
		
		$this->view->allCats = $allCats;
		$this->view->data = $data;
		$this->view->headTitle('New Demo');
		$this->view->menu = array('exercise', 'newdemo');
	}
	public function editFolderAction()
	{
		$objFolder = new Models_Folder();
// 		$objFile = new Models_File();
		$objCat = new Models_ContentCategory();
		
		$gid     = $this->_getParam('id', false);
		if (false == $gid) {
			$this->_redirect('exercise/admin/manage-folder');
		}
// 		echo "<pre>";print_r($gid);die;
		
		$data   = $this->_getParam('data', false);
		
		/**
		 * Get all categories
		 */
		$allCats = $objCat->getAll()->toArray();
		
		
		$errors = array();
		if (false !== $data) {
			$newFolder = array(
				 'title' => $data['title'],
				 'description' => $data['description'],
				 'subject_id' => $data['subject_id'],
				 'update_date' => time()
				 
				 );
			/**
			 * Remove empty files
			 */
			if (is_array(@$data['file'])) {
				foreach ($data['file'] as $index => $file) {
					if (null == $file) {
						unset($data['file'][$index]);
					} else {
						$data['file'][$index] = Nine_Function::getImagePath($file);
					}
				}
			}
			$newFolder['files'] = implode('||', $data['file']);
			try {
				/**
				 * Update
				 */
				//echo '<pre>';print_r($gid);die;
				$objFolder->update($newFolder, array('folder_id=?' => $gid));
				/**
				 * Message
				 */
				$this->session->folderMessage =  array(
						'success' => true,
						'message' => Nine_Language::translate('Folder is updated successfully.')
				);
		
				$this->_redirect('exercise/admin/manage-folder');
			} catch (Exception $e) {
				$errors = array('main' => Nine_Language::translate('Can not insert into database now'));
			}
		} else {
			/**
			 * Get old data
			 */
			$data = $objFolder->getFolderById($gid);
			
		
			if (false == $data) {
				$this->session->folderMessage = array(
						'success' => false,
						'message' => Nine_Language::translate("Folder doesn't exist.")
				);
				$this->_redirect('exercise/admin/manage-folder');
			}
			
			/**
			 * Format image
			 */
			
			//echo "<pre>";print_r($data);die;
			$data['files'] = explode('||', $data['files']);
			if (! is_array($data['files'])) {
				$data['files'] = array();
			}
			$data['files'] = array_pad($data['files'], 50, null);
// 			echo "<pre>";print_r($data);die;
		}
		/**
		 * Prepare for template
		 */
		$this->view->allCats = $allCats;
		$this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
		$this->view->errors = $errors;
		$this->view->data = $data;
		$this->view->headTitle(Nine_Language::translate('Edit Folder'));
		$this->view->menu = array('exercise','');
		$this->view->fullPermisison = $this->checkPermission('edit_folder', null, '*');
	}
	public function viewDemoAction()
	{
		$objFolder = new Models_Folder();
		$objFile = new Models_File();
		$objCat = new Models_ContentCategory();
		
		$gid     = $this->_getParam('id', false);
		if (false == $gid) {
			$this->_redirect('exercise/admin/manage-folder');
		}
		$data = $objFolder->getFolderById($gid);
			
		
		if (false == $data) {
			$this->session->folderMessage = array(
					'success' => false,
					'message' => Nine_Language::translate("Folder doesn't exist.")
			);
			$this->_redirect('exercise/admin/manage-folder');
		}
			
		/**
		 * Format image
		 */
			
		//echo "<pre>";print_r($data);die;
		$data['files'] = explode('||', $data['files']);
		if (! is_array($data['files'])) {
			$data['files'] = array();
		}
	//	echo "<pre>";print_r($data);die;
		$content = "";
		$tmp = array();
		foreach ($data['files'] as $item)
		{
			$url = Nine_Registry::getConfig("liveSite")."/". $item;
			//$content = file_get_contents($url);
			$path_parts = pathinfo($url);
			
			if($path_parts['extension'] == "js")
			{
				$file = array('type' => "js", 'url'=> $item);
				array_push($tmp, $file);
			//		echo "<pre>";print_r(file_get_contents($url));die;
// 				echo "<pre>";print_r($path_parts['extension']);die;
				//$url = Nine_Registry::getConfig("liveSite")."/". $item;
				//$content = $content . '<script>' . file_get_contents($url) . '</script>';
				//echo "<pre>";print_r($content);die;
				//$content .= '<p>aaaaaa</p>';
				
			}
			if($path_parts['extension'] == "css")
			{
				$file = array('type' => "css", 'url'=> $item);
				array_push($tmp, $file);
				//$content = $content . '<style>' . file_get_contents($url) . '</style>';
				//$content .= '<link href="" rel="stylesheet" type="text/css" />';
			}
			if($path_parts['extension'] == "html")
			{
				$file = array('type' => "html", 'url'=> $item);
				//$content = file_get_contents($url);
				array_push($tmp, $file);
				//$content .= file_get_contents($url);
				// 				echo "<pre>";print_r($path_parts['extension']);die;
			}
		}
		
		//$content = $content . "</html>";
		//echo "<pre>";print_r($content);die;
		$this->view->content = $content;
		$this->view->data = $tmp;
		
	}
}

?>